import { Component } from 'react';
import BookLoader from './BookLoader';
import CardIndex from './CardIndex';

export default
class TBooks extends Component {

  constructor(props) {
    super(props);

    this.baseUrl = props.BaseUrl || '.';
    this.baseUrl += '/data/';
    this.bookListUrl = props.BookList || 'books.json';

    this.state = {
      BookList:[],
      SelectedIndex: -1,
    }

    this.handleSelectedBookChanged = this.handleSelectedBookChanged.bind(this);
  }

  componentDidMount() {
    const url = `${this.baseUrl}${this.bookListUrl}`;
    // console.log(url);
    fetch(url)
    .then( response=>{ console.log(response); return response.json(); } )
    .then( json => {
      console.log( json );
      if( json.BookList ) {
        this.setState( { BookList: json.BookList })
      }
    });
  }

  handleSelectedBookChanged(event) {
    this.setState({ SelectedIndex: event.target.id });
  }

  handleAuthorClicked( event ) {
    // todo: 按照作者分类图书
  }

  render(){
    if( this.state.SelectedIndex < 0 || this.state.SelectedIndex >= this.state.BookList.length ) {
      return(
        <div className='App'>
          <div className='flex-row flex-align-center'>
            <h1> 交互式图书馆 </h1>
          </div>
          {<CardIndex 
            Indexes = {this.state.BookList}
            onIndexChanged = { this.handleSelectedBookChanged }
            onAuthorClicked = { this.handleAuthorClicked.bind(this) }
          />}
        </div>
      );
    }
    else {
      return <BookLoader 
        BaseUrl = { this.baseUrl }
        Book={this.state.BookList[this.state.SelectedIndex]}
      />
    }
  }
}